<template>
  <div class="common-list-container__v2" v-loading.fullscreen.lock="loading">
    <!--s 头部搜索栏 -->
    <div class="common-list-header__v2">
      <el-button-group>
        <el-button :type="reviewType == 1 ? 'primary' : 'ghost'" @click="selectReviewType(1)">人工回访</el-button>
        <el-button :type="reviewType == 2 ? 'primary' : 'ghost'" @click="selectReviewType(2)">自动回访</el-button>
      </el-button-group>
      <div class="input-with-append-search">
        <el-input class="search-input" placeholder="请输入工单编号/客户信息" v-model="searchParams.keyword" v-trim:blur>
          <el-button type="primary" slot="append" @click="searchParams.pageNum=1;search();trackEventHandler('search')" native-type="submit">搜索</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams">重置</el-button>
      </div>
      <span class="advanced-search-btn pointer" @click.self="panelSearchAdvancedToggle">
        <i class="iconfont icon-filter" @click.self="panelSearchAdvancedToggle"></i>
        高级搜索
      </span>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div class="common-list-view-header__v2">
        <!-- todo TASK_BATCH_CLOSE 权限-->
        <div>
          <el-button-group v-if="reviewType == 1" class="mar-r-16">
            <el-button :type="isReview == 2 ? 'primary' : 'ghost'" @click="reviewWorkTask(2)">全部</el-button>
            <el-button :type="isReview == 1 ? 'primary' : 'ghost'" @click="reviewWorkTask(1)">已回访</el-button>
            <el-button :type="isReview == 0 ? 'primary' : 'ghost'" @click="reviewWorkTask(0)">未回访</el-button>
          </el-button-group> 
          <el-button-group v-else class="mar-r-16">
            <el-button :type="isEvaluate == 2 ? 'primary' : 'ghost'" @click="reviewWorkTask(2)">全部</el-button>
            <el-button :type="isEvaluate == 1 ? 'primary' : 'ghost'" @click="reviewWorkTask(1)">已评价</el-button>
            <el-button :type="isEvaluate == 0 ? 'primary' : 'ghost'" @click="reviewWorkTask(0)">未评价</el-button>
          </el-button-group> 
          <el-button type="primary" @click="payVisit()">发送回访短信</el-button>
          <el-tooltip content="当前视图有新工单时，请通知我">
            <i
              class="iconfont icon-dingyuetongzhiguanli ml_20 pointer"
              :class="hasSub ? 'actived' : ''"
              @click="toggleTaskSubscribe">
              {{ hasSub ? '已订阅': '未订阅'}}
            </i>
          </el-tooltip>
        </div>
        <div>
          <el-dropdown trigger="click" v-if="exportPermission && isButtonDisplayed">
            <span class="el-dropdown-link cur-point" @click="trackEventHandler('moreAction')">
              更多操作
              <i class="iconfont icon-fdn-select"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportTask(false)">导出</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportTask(true)">导出全部</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span class="el-dropdown-link cur-point mar-l-12" @click="showAdvancedSetting">
            选择列
            <i class="iconfont icon-fdn-select"></i>
          </span>
        </div>
      </div>
      <div
        v-show="multipleSelection.length"
        class="common-list-selection__v2 mt_8"
      >
        已选择
        <span>
          {{ multipleSelection.length }}
        </span>
        条
        <span class="pointer" @click="toggleSelection">清空</span>
      </div>
      <!--s 表格 -->
      <el-table
        ref="table"
        class="common-list-table__v2 mt_8"
        stripe
        :data="taskPage.content"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        header-row-class-name="common-list-table-header__v2"
      >
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
        ></el-table-column>
        <el-table-column
          v-if="column && column.show && column.visable"
          v-for="column in columns"
          show-overflow-tooltip
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
        >
          <template slot-scope="scope">
            <template v-if="column.renderCell">
              <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!(reviewType == 2 && isEvaluate == 0)"
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <template v-if="(reviewType == 1 && scope.row.isReview == 1) || reviewType == 2">
              <el-button type="text" size="small" :style="{color: '#909399 !important'}" @click="reviewTask(scope.row,true)">查看</el-button>
            </template>
            <template v-if="reviewType == 1 && scope.row.isReview == 0  && scope.row.inApprove != 1" >
              <el-button type="text" size="small" :disabled="pending" @click="reviewTask(scope.row,false)">回访</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--e 表格 -->
      <!--s 分页信息 -->
      <div class="common-list-table-footer__v2 mt_12">
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          :layout="defaultTableData.defaultLayout"
          :total="taskPage.totalElements"
        >
        </el-pagination>
      </div>
      <!--e 分页信息 -->
    </div>
    <!--e 内容 -->

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="search"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="advanceSearchColumn"/>
    </base-search-drawer>
    <!-- 选择列 --> 
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    <!-- start 导出工单 -->
    <base-export-group
      ref="exportPanel"
      :alert="exportAlert"
      :columns="exportColumnList.length ? exportColumnList : exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      method="post"
      :action="taskListExport_2"
    />
    <!-- end 导出工单 -->
    <!-- start 回访弹窗 -->
     <div class="task-feedback-container">
       <task-feedback-dialog
          ref="feedbackDialog"
          :from="from"
          :task="task"
          :readonly="readonly"
          :evaluate-config="evaluateConfig"
          @proposeApprove="proposeApprove"
        />
     </div>
    
    <!-- end 回访弹窗 -->
  </div>
</template>

<script>
// api
import * as TaskApi from '@src/api/TaskApi';
// model
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields, getEvaluateExportFields, getAutoEvaluateExportFields, getSystemExportFields} from './fields';
// components
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import FeedbackDialog from '@src/modules/task/view/components/TaskFeedback/FeedbackDialog';

import formatColumn from 'packages/BaseTableCell/formatColumn';
import { formatDate } from 'pub-bbx-utils';
import { checkButtonDisplayed } from '@src/util/dom';
import { safeNewDate } from '@src/util/time';
import { defaultTableData } from '@src/util/table'
/* export & import */
import { taskListExport_2 } from '@src/api/Export';
// import { eventListImport_1, eventListImportTem_1 } from '@src/api/Import';

const MAXCHECK = 500;
let cardExportColumns = [];


export default {
  name: 'task-review-list',
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      from: '',
      task: {},
      readonly: false,
      reviewType: 1,
      isReview: 0,
      isEvaluate: 0,
      hasSub: 1,
      exportColumnList:[],
      exportColumns:[],
      taskApproveId: '',
      currentTaskType: {},
      taskTypes: [],
      taskFields: [],
      taskReceiptFields: [],
      multipleSelection: [],

      searchParams: {
        keyword: '',
        isSubscribe: false,
        pageSize: 10,
        pageNum: 1,
        sorts: []
      },
      taskPage: new Page(),

      visible: false,
      columns: [],
      columnNum: 1,

      loading: false,
      pending: false,
      taskListExport_2
    }
  },
  computed: {
    
    // 是否有导出权限
    exportPermission(){
      return true
    },
    // zr_todo:
    taskConfig() {
      return {};
    },
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this),
        ...this.taskFields.filter(filed => { // 过滤重复项
          return !getColumnFields(this).some(item => item.field === filed.fieldName);
        })
      ].filter(item => 
        item.isSearch && item.isSearch == 1
      );
    },
    taskTypeList() {
      return [
        {
          name: '全部', templateId: ''
        },
        ...this.taskTypes
      ]
    },
    serviceTypeDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceType') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return ['全部', ...dataSource];
    },
    serviceContentDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceContent') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return ['全部', ...dataSource];
    },
    levelDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'level') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return ['全部', ...dataSource];
    },
    /** 当前选中的工单ids */
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },
    customerSetting(){
      // todo替换
      return {linkmanOn:true, addressOn:true, productOn:true}
    },
    sysFieldsSetting(){
      // todo替换
      return {hasServiceType:true, hasServiceContent:true, hasDescription:true, hasLevel:true}
    },
    paymentConfig(){
      // todo替换
      return {version:1}
    },
    isTaskManager(){
      // todo替换
      return true
    },
    evaluateConfig(){
      // todo替换
      return {"modifyEvaluate":true,"modifyEventEvaluate":true,"autoCloseTask":true,"useStarEvaluate":true,"useTagEvaluate":true,"starEvaluateNotNull":false,"starEvaluateFeilds":["starEvaluate1","starEvaluate2","starEvaluate3","starEvaluate4","starEvaluate5","starEvaluate6"],"starEvaluates":["服务态度","服务效率","服务质量"],"tagEvaluates":["速度快","很热情","质量高","技术强","有点差"],"reviewViewAuthiroty":"hasTaskViewAuthiroty"}
    }
  },
  watch: {
    taskFields() {
      this.columns = [
        ...getColumnFields(this),
        ...this.taskFields.filter(f => {
          return f.isSystem !== 1 
          && !['attachment', 'separator', 'info', 'autograph'].includes(f.formType)
        })
      ].map(field => {
        return {
          ...formatColumn(field),
          field: field.field || field.fieldName
        }
      });
    },
    'currentTaskType.id': {
      handler(newVal, oldVal) {
        if(newVal && newVal != oldVal) {
          this.fetchTaskFields();
        }
      }
    },
    reviewType: {
      handler(newValue, oldValue) {
        this.handleExportColumns(newValue);
        this.exportColumnList = [...this.exportColumns, ...cardExportColumns];
      }
    }  
  },
  methods: {
    reviewWorkTask(type){
      if(this.reviewType == 1) {
        this.isReview = type
      } else {
        this.isEvaluate = type
      }
      this.fetchTaskList();     
    },
     /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.taskPage.totalElements > max
        ? '为了保障响应速度，暂不支持超过5000条以上的数据导出，请您分段导出。'
        : null;
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * @description 导出工单
     * @param {Boolean} exportAll 是否导出全部
     */
    exportTask(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}工单数据.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert('请选择要导出的数据');
        ids = this.selectedIds;
      }

      this.$refs.exportPanel.open(ids, fileName);
    },
     /**
     * 导出数据
     */
    exportData(number, list = []) {
      const export_list = this.exportColumnList.length ? this.exportColumnList : this.exportColumns
      if (number === 3) {
        let cardField = []
        export_list.filter((item, index) => {
          return index > 2
        }).forEach(v => {
          v.columns.forEach(item => {
            cardField.push(item)
          })
        })
        return cardField.map(v => {
          let bool = list.some(item => {
            if (v.exportAlias) {
              return v.exportAlias === item
            } 
            return v.fieldName === item
            
          })
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName
          }
        }).filter(item => {
          return item
        })
      }

      return export_list[number].columns.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          } 
          return v.fieldName === item
          
        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const {
        receiptChecked,
        systemChecked,
        taskChecked,
        evaluateChecked
      } = checkedMap
      const all = {
        ...this.searchParams,
        taskIds: this.selectedIds,
      };
      let exportAll = !ids || !ids.length;

      let exportSearchModel = {
        typeId: this.currentTaskType.id,
      };
      let params = {
        exportSearchModel: JSON.stringify({
          ...all,
          ...{
            exportTotal: exportAll
              ? this.taskPage.totalElements : this.selectedIds.length,
          },
        }),
      };
      // 附加
      let cardFieldChecked = []
      for (let key in checkedMap) {
        if (key.indexOf('annexChecked') !== -1) {
          cardFieldChecked = [...cardFieldChecked, ...checkedMap[key]]
        }
      }
      cardFieldChecked = cardFieldChecked.filter(item => {return item})
      /** ********************* *********************/
      // 工单信息
      let export_task = this.exportData(0, taskChecked)
      // 回执信息
      let export_receipt_task = this.exportData(1, receiptChecked)
      // 系统信息
      let export_sys_task = this.exportData(2, systemChecked)
      // 附加信息
      let export_card_fiel_task = cardFieldChecked.length ? this.exportData(3, cardFieldChecked) : cardFieldChecked
      console.log('导出数据----附加', export_card_fiel_task)
      // 评价信息
      let export_evaluate_task = this.exportData(4, evaluateChecked)
      params['exportOneRow'] = exportOneRow
      params['data'] = exportAll ? '' : this.selectedIds.join(',');
      params['typeId'] = exportSearchModel.typeId;
      params['receiptChecked'] = export_receipt_task
        .map((item) => {
          if (item === 'spare_name') {
            item = 'spare_name,spare_serialNumber,spare_type,spare_number,spare_cost'
          }
          if (item === 'service_name') {
            item = 'service_name,service_type,service_number,service_cost'
          }
          if (item === 'balance_total') {
            item = 'balance_total,balance_discount,balance_sum'
          }
          return item;
        })
        .join(',');
      params['sysChecked'] = export_sys_task
        .map((item) => {
          return item;
        })
        .join(',');
      params['checked'] = export_task
        .map((item) => {
          if (item === 'product') {
            item = 'product,productSN'
          }
          return item;
        })
        .join(',');
      params['cardFieldChecked'] = export_card_fiel_task.filter(item => {
        return item
      }).join(',')
      params['evaluateChecked'] = export_evaluate_task
        .map((item) => {
          return item;
        })
        .join(',');
      return params;
    },
    // 人工回访 自动回访
    selectReviewType(type) {
      this.reviewType = type;
      this.columns = getColumnFields(this);
      this.fetchTaskList();
    },
    // 回访 查看
    async reviewTask(item, readonly){
      if (this.pending) return;
      this.pending = true;
      this.task = item;
      this.from = 'reviewList'
      this.readonly = readonly;
      try {
        // 检验附加组件是否必填
        const res = await TaskApi.checkNotNullForCard({ id: this.task.id, flow: 'review' });

        this.pending = false;

        if (res.status == 1) return this.$platform.alert(res.message);
        this.$refs.feedbackDialog.openDialog();

      } catch (e) {
        console.error('feedback task error', e);
      }
    },
    /** 取消或订阅工单 */
    async toggleTaskSubscribe() {
      let action = this.hasSub ? TaskApi.taskUnSubscribe : TaskApi.taskSubscribe;
      let tip = this.hasSub ? '已取消订阅通知' : '已订阅通知';
      try {
        let res = await action({module:'taskReview'});
        if(res.status == 0){
          this.$platform.alert(tip);
          this.hasSub = this.hasSub == 0 ? 1 : 0;
        }else {
          this.$platform.alert(res.message);
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 重新发送回访信息
    async payVisit(form) {
      let selectedIds = this.selectedIds;
      var msg = '是否对所选的工单重新发送回访短信？';
      if(form){
        selectedIds = [form.id];
        msg = '是否发送回访短信？';
      }
      if (!selectedIds.length) {
        this.$platform.alert('请选择数据');
        return;
      }
      try {
        let confirm = await this.$platform.confirm(msg);
        if (confirm) {
          const params = {type: this.reviewType == 1 ? 'ARTIFICIAL' : 'AUTO_REVIEW', contentList: selectedIds};
          const { message } = await TaskApi.sendReviewMessage(params);
          this.$platform.alert(message);
        }
      } catch (error) {
        console.log(error);
      }
    },
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：回访工单-搜索事件');
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent('pc：回访工单-更多操作事件');
        return;
      }
    },
    /**  获取工单类型 */
    fetchTaskTypesMap() {
      // 如果工单类型列表数据已存在则不查询
      if (this.taskTypes.length > 0) return
    
      return (
        TaskApi.getTaskTypesMap().then((data) => {
          let isSuccess = data.success
          if (!isSuccess) return
        
          this.taskTypes = data?.result || []
          // key : 工单类型id(string) -> value: TaskType
          this.taskTypesMap = (
            this.taskTypes
              .reduce((acc, currentTaskType) => {
                acc[currentTaskType.templateId] = currentTaskType
                return acc
              }, {})
          )
        }).catch(err => {
          console.error(err)
        })
      )
    },
    /** 打开高级搜索 */
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：工单关闭列表-高级搜索事件');
      this.visible = true;
    },
    /** 关闭高级搜索弹框 */
    closeDrawer(){
      this.visible = false;
    },
    resetParams () {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
          field.show = true;
        });
        this.taskFields = result;
      }).catch(err => {
        console.error(err);
      });
    },
    /**
     * @description 获取工单回执字段列表
     * @return {Promise}
     */
    fetchTaskReceiptFields() {
      let params = {
        templateId: this.currentTaskType.id || '',
        tableName: 'task_receipt',
      };
      return TaskApi.getTaskTemplateFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task_receipt';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    /** 获取列表数据 */
    fetchTaskList(searchParams) {
      let params = {
        ...this.searchParams,
        ...searchParams
      }
      this.loading = true;
      TaskApi.search(params)
        .then((res) => {
          this.loading = false;
          this.taskPage = res.result || [];
        })
        .catch(err => {
          this.loading = false;
          console.error(err);
        })
    },
    /** 搜索事件 */
    search () {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      
      if(advancedSearchParams.taskType) {
        let typeId = advancedSearchParams.taskType;
        let taskType = this.taskTypes.find(item => item.templateId === typeId);
        this.currentTaskType = {
          id: typeId,
          name: taskType && taskType.name
        };
      }

      this.fetchTaskList(advancedSearchParams);
      this.closeDrawer();
    },
    /** 打开选择列 */
    showAdvancedSetting(){
      window.TDAPP.onEvent('pc：回访工单列表-选择列事件');
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /** 选择列更新事件 */
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.$message.success(this.$t('common.base.saveSuccess'));
      })
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    /** 表格选择操作: zr_todo */
    handleSelection(selection) {
      let selected = [];

      selected = [
        ...this.multipleSelection,
        ...selection.filter(item => {
          return !this.multipleSelection.some(s => s.id === item.id);
        })
      ];

      if(selected.length > MAXCHECK) {
        return this.$platform.alert(`最多只能选择${MAXCHECK}条数据`);
      }
      
      this.multipleSelection = selection;
    },
    /** 排序变化  */
    sortChange(option) {
      let {column, order, prop} = option;
      if(column === null) {
        this.searchParams.sorts = {};
      }else{
        this.searchParams.sorts = [{
          property: column.isSystem ? prop : `attribute.${prop}`,
          direction: order === 'ascending' ? 'ASC' : 'DESC',
        }]
      }
      
      this.search();
    },
    /** 清空选择框 */
    toggleSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },
    /** 页码跳转 */
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.taskPage.list = [];
      this.search();
    },
    /** 页大小改变 */
    handleSizeChange(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;

      this.search();
    },
    /** 发起审批 */ 
    proposeApprove(data) {
      this.$refs.proposeApprove.openDialog(data);
    },
    async _exportColumns() {
      cardExportColumns = await this.getCardDetailList(this.currentTaskType.id);
      this.handleExportColumns(this.reviewType);
      this.exportColumnList = [...this.exportColumns, ...cardExportColumns];
      console.log('exportColumnList', this.exportColumnList);
    },
    handleExportColumns(reviewType){
      let { taskFields, taskReceiptFields } = this
      // 工单信息
      let taskSelfFields = [];
      // 回执信息
      let taskReceiptSystemFields = [{
        id: 5460,
        isSystem: 1,
        fieldName: 'spare_name',
        field: 'spare_name',
        displayName: '备件',
        label: '备件',
        formType: 'text',
        isNull: 1,
        isSearch: 0,
      },
      {
        id: 5460,
        isSystem: 1,
        fieldName: 'service_name',
        field: 'service_name',
        displayName: '服务项目',
        label: '服务项目',
        formType: 'text',
        isNull: 1,
        isSearch: 0,
      },
      {
        id: 5460,
        isSystem: 1,
        fieldName: 'balance_total',
        field: 'balance_total',
        displayName: '费用信息',
        label: '费用信息',
        formType: 'text',
        isNull: 1,
        isSearch: 0,
      },
      ];

      // 工单信息逻辑
      let linkman_list = '',
        address_list = '',
        product_list = ''
      taskSelfFields = taskFields.filter(item => {
        return item.formType !== 'attachment'
      })
      if (taskFields.length) {
        let first = taskFields.filter(item => {
          return item.displayName === '客户'
        })[0]
        if (first.setting.customerOption.linkman) {
          linkman_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmName',
            displayName: '联系人',
            exportAlias: 'customerLinkman',
            formType: 'select',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            show: true,
            guideProfessions: [],
            isGuideData: false,
            guideData: false,
          },
          {
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmPhone',
            exportAlias: 'customerPhone',
            displayName: '电话',
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.address) {
          address_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'taddress',
            exportAlias: 'customerAddress',
            displayName: '客户地址',
            formType: 'address',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.product) {
          product_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'product',
            exportAlias: 'product',
            displayName: '产品',
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
      }
      taskSelfFields.forEach((item, index) => {
        if (item.displayName === '工单编号') {
          taskSelfFields.splice(index + 1, 0, {
            id: 476,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'templateName',
            exportAlias: 'templateName',
            displayName: '工单类型',
            formType: 'text',
            defaultValue: null,
            isNull: 0,
            isSearch: 1,
            placeHolder: null,
            setting: {
              customerNameDuplicate: false,
            },
            orderId: 0,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          })
        }
        if (item.displayName === '客户') {
          if (linkman_list) {
            taskSelfFields.splice(index + 1, 0, linkman_list[0], linkman_list[1])
          }
          if (address_list) {
            taskSelfFields.splice(index + linkman_list.length + 1, 0, address_list[0])
          }
          if (product_list) {
            taskSelfFields.splice(index + linkman_list.length + address_list.length + 1, 0, product_list[0])
          }
        }
      })
      taskSelfFields.map(item => {
        item.label = item.displayName
        item.export = true
        return item
      })
      // 回执信息逻辑
      taskReceiptSystemFields = [
        ...taskReceiptSystemFields,
        ...taskReceiptFields.filter(item => {
          return (item.isSystem === 0 && item.formType !== 'attachment')
        })
      ].map((field) => {
        field.export = true;
        return field;
      });
      let taskEvaluateFields = []
      if(reviewType == 1) {
        taskEvaluateFields = getEvaluateExportFields()
      } else {
        taskEvaluateFields = getAutoEvaluateExportFields()
      }
      console.log('taskEvaluateFields', taskEvaluateFields);
      this.exportColumns = [
        {
          label: '工单信息',
          value: 'taskChecked',
          columns: taskSelfFields,
        },
        {
          label: '回执信息',
          value: 'receiptChecked',
          columns: taskReceiptSystemFields,
        },
        {
          label: '评价信息',
          value: 'evaluateChecked',
          columns: taskEvaluateFields.map(item => {
            item.export = true
            item.label = item.displayName
            return item
          }),
        },
        {
          label: '系统信息',
          value: 'systemChecked',
          columns: getSystemExportFields(this).filter(item=>{
            return item.show;
          }).map(item => {
            item.export = true
            item.label = item.displayName
            return item
          }),
        },
      ];
    },
    async getCardDetailList(typeId) {
      const res = await TaskApi.getCardDetailList({
        typeId
      });
      let list = res.map((item, index) => {
        if (item.canRead) {
          let columns, endAddress = {
              displayName: '位置',
              fieldName: 'endAddress',
            }, startAddress = {
              displayName: '位置',
              fieldName: 'startAddress',
            }
          if (item.specialfrom === '工时记录') {
            let list = []
            // 添加固定导出参数
            item.fields.splice(item.fields.map((v, i) => {
              if (v.fieldName === 'endTime') {
                return i + 1
              }
            }).filter(v => {
              return v
            })[0], 0, endAddress)

            item.fields.splice(item.fields.map((v, i) => {
              if (v.fieldName === 'startTime') {
                return i + 1
              }
            }).filter(v => {
              return v
            })[0], 0, startAddress)

            item.fields.forEach(v => {
              if (v.fieldName !== 'remark' && v.fieldName !== 'attachment' ){
                list.push(v)
              }
            })
            list.map((v, i) => {
              if (!v.map) {
                v.fieldName = `${item.cardId}_${v.fieldName}`
              }
            })

            item.fields = [...list, ...[{displayName: '行程距离',
              fieldName: `${item.cardId}_distance`}]]
          } else {
            item.fields = [...item.fields, ...[{displayName: '操作人',
              fieldName: `cu_${item.cardId}`}, {displayName: '操作时间',
              fieldName: `ct_${item.cardId}`}]]
          }
          columns = item.fields.map((v, i) => {
            return {
              export: item.canRead,
              label: v.displayName,
              exportAlias: v.fieldName,
              ...v,
            };
          }).filter(v => {
            return v.formType !== 'attachment'
          });
          return {
            value: `annexChecked${index}`,
            label: `附加组件：${item.cardName}`,
            inputType: item.inputType,
            columns,
          };
        }
      }).filter(item => {
        if (item) {
          return item
        }
      })
      return list || [];
    },
  },
  mounted() {
    this.columns = getColumnFields(this);
    // 获取工单类型列表
    this.fetchTaskTypesMap();
    this.fetchTaskList();
    this.$nextTick(()=>{
      Promise.all([this.fetchTaskFields(), this.fetchTaskReceiptFields()])
        .then((res) => {
          console.log(res[0], 'list组件')
          this.$set(this, 'taskFields', res[0] || []);
          this.$set(this, 'taskReceiptFields', res[1] || []);
          this._exportColumns();
        })
        .catch((err) => {
          console.warn(err);
        });
    })
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    [FeedbackDialog.name]: FeedbackDialog
  }
}
</script>

<style lang="scss" scoped>
.common-list-header__v2{
  align-items: center;
  .input-with-append-search {
    display: flex;
    flex: 1;
    justify-content: flex-end;
    margin-right: 20px;
  }
}

.search-input{
  width: 440px;
}

.search-input__append{
  @include backgroundColorImportant();
  color: #fff !important;
  border-radius: 0 4px 4px 0 !important;
}

.advanced-search-btn{
  @include fontColor;
}

.icon-dingyuetongzhiguanli{
  font-size: 14px;
}

.icon-dingyuetongzhiguanli.actived{
  @include fontColor;
}

.el-input-group__append{
  border-radius: 0 4px 4px 0;
}
</style>

<style lang="scss">
// 弹窗
.task-feedback-container{

  // 按钮
  .el-button {
    padding-left: 0;
    padding-right: 0;

    font-weight: normal;
    border-radius: 4px;

    &.el-button--small {
      font-size: $font-size-base;
      padding: 8px;
    }
  }

 .base-modal {
    .base-modal-body {
      padding: 20px;
  
      .base-modal-content {
        textarea {
          width: 100%;
        }
        
        p {
          margin-bottom: 8px;
  
          &.tips {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
  }

  .evaluate-degree-img {
    width: 24px;
    height: 24px;
    margin-right: 2px;
    display: inline-block;
    vertical-align: middle;

    background: url(../../../../assets/img/task/review-degree.png) no-repeat;
    background-size: 24px 144px;

    &.review-degree-satisfy {
      background-position: 0 0;
    }

    &.review-degree-commonly {
      background-position: 0 -24px;
    }

    &.review-degree-unsatisfy {
      background-position: 0 -48px;
    }

    &.review-degree-satisfy-active {
      background-position: 0 -72px;
    }

    &.review-degree-commonly-active {
      background-position: 0 -96px;
    }

    &.review-degree-unsatisfy-active {
      background-position: 0 -120px;
    }
  }

  .star-evaluate-row-content {
    flex: 1;

    .star-evaluate-row {
      display: flex;
      margin-bottom: 10px;

      .star-title {
        width: 86px;
        margin-right: 6px;
      }
    }
  }

  .evaluate-tag {
    .evaliate-tag-item {
      display: inline-block;
      padding: 2px 8px;
      margin: 0 10px 10px 0;
      font-size: 12px;
      border: 1px solid #e5e5e5;
      background-color: #f8f7f6;
      border-radius: 2px;
      color: #757575;
    }

    .evaliate-tag-active,
    input[type='checkbox']:checked ~ span {
      color: #00d1d3;
      background-color: #f5fffd;
      border-color: #00d1d3;
    }
  }
}
</style>